<?php

namespace interface\pda;
use control\adIndexClass;

require_once 'app.php';

class index
{
	use app;

	protected array         $powerAll          = [];
	protected array         $controlPower      = [];
	protected static array  $user              = [];                //账户信息
	protected static string $stid              = '';                //'aefa5c6f4022e2ca';//'Ore126054470Vd';//员工ID
	protected array         $control           = [];                //员工信息
	protected array         $controlJob        = [];                //职位
	protected array         $controlDepartment = [];                //部门
	protected static string $coid              = '';
	public array            $resp              = [];
	public int              $code              = 0;
	protected array         $timeOption        = ['今天', '近7天', '近30天', '自定义'];
	private int             $loginState        = 0;                                                                                                                                                              //登录状态  1为登录
	private array           $whiteCla          = ['loginApp'];                                                                                                                                                   //无需登录的类
	private string          $loginWarn         = '';                                                                                                                                                             //登录提示


	public function __construct()
	{
		$this->init();                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             //常用参数
		$cla   = $this->get('cla') ?? '';                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      // 类型
		$token = !empty($this->header['Auth']) ? $this->header['Auth'] : '';
		if (!in_array($cla, $this->whiteCla)) {
			//以上三类不需要登录
			$warn = $this->checkToken($token);
			if ($warn !== true) {
				$this->loginState = -1;
				$this->loginWarn  = $warn;
			} else {
				$this->loginState = 1;
				self::$stid       = $this->rGet($token);
				//设置coid
				self::$coid     = self::findCoid();
				self::$user     = query('user', "stid = '" . self::$stid . "'");
				$this->powerAll = $GLOBALS['powerAll'];
				// 重写adIndex类参数
				adIndexClass::$stid = self::$stid;
				adIndexClass::$coid = self::$coid;
				adIndexClass::$user = self::$user;

				$this->control           = query('staff', "stid = '" . self::$stid . "'");
				$this->controlJob        = query('job', "id = '" . $this->control['jobId'] . "'");
				$this->controlDepartment = query('department', " id = '" . $this->controlJob['departmentId'] . "'");
				$this->controlPower      = adIndexClass::getUserPower();
			}
		}
	}

	/**
	 * 主函数
	 *
	 * @return void
	 */
	public function main(): void
	{
		$cla = $this->get('cla') ?? '';     // 类型
		$act = $this->get('fun') ?? 'index';// 方法
		if (!$cla) {
			exit('<h2>Error</h2>');
		} else {
			if (!in_array($cla, $this->whiteCla) && in_array($this->loginState, [-1, 0])) {
				$this->resp['warn'] = $this->loginWarn;
				$this->code         = $this->loginState;
				return;
			}
			if (!in_array($cla, ['index', 'app'])) {
				$cla .= str_contains($cla, 'Class') ? '' : 'Class'; // 追加Class 名
			}
			$cla = __NAMESPACE__ . '\\' . $cla;
			$obj = new $cla();
            if (method_exists($obj, $act) && is_callable([$obj, $act])) {
				$obj->$act();
			} else {
				exit('<h2>Modules don\'t exist</h2>');
			}
		}
	}

	/**
	 * 查找当前使用的coid
	 *
	 * @return mixed
	 */
	public static function findCoid(): mixed
	{
		$record = query('user_setting', "stid = '" . self::$stid . "' and type = '当前使用账套'");
		if (empty($record['id'])) {
			$company = query('company', "isDel = 0");
			self::updateCoidRecord($company['coid']);
			return $company['coid'];
		}
		return $record['value'];
	}

	/**
	 * 记录当前使用的账套
	 */
	public static function updateCoidRecord($coid): bool
	{
		if (empty($coid)) {
			return false;
		}
		$record = query('user_setting', "stid = '" . self::$stid . "' and type = '当前使用账套'");
		if (empty($record['id'])) {
			$warn = static::insert(array(
				'table' => 'user_setting',
				'field' => [
					'type'  => '当前使用账套',
					'value' => $coid,
					'stid'  => self::$stid,
				],
			));
		} else {
			$warn = static::update(array(
				'table' => 'user_setting',
				'field' => [
					'value' => $coid,
				],
				'where' => "id = '$record[id]'",
			));
		}
		if (in_array($warn, ['新增成功', '更新成功'])) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 检查token是否失效
	 */
	public function checkToken($token): bool|string
	{
		if (!$token) {
			return '你未登录，请登录';
		} else {
			$stid = $this->rGet($token);
			if (!$stid) {
				return '登录凭证已过期，请重新登录';
			} else {
				$staff = query('staff', " state !='离职' AND stid = '$stid' ");
				if (!$staff) {
					return '未找到此用户';
				} else {
					return true;
				}
			}
		}
	}

}

exit((new index())->main());
